package net.wicp.tams.component.components;

import java.util.List;

import org.apache.commons.collections.Predicate;
import org.apache.tapestry5.Asset;
import org.apache.tapestry5.BindingConstants;
import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.Link;
import org.apache.tapestry5.StreamResponse;
import org.apache.tapestry5.SymbolConstants;
import org.apache.tapestry5.annotations.Events;
import org.apache.tapestry5.annotations.Import;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.internal.util.CaptureResultCallback;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.annotations.InjectService;
import org.apache.tapestry5.ioc.annotations.Symbol;
import org.apache.tapestry5.ioc.internal.util.CollectionFactory;
import org.apache.tapestry5.json.JSONArray;
import org.apache.tapestry5.services.AssetSource;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.services.RequestGlobals;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import net.wicp.tams.common.web.EasyUiAssist;
import net.wicp.tams.common.web.easyuibean.EasyUINode;
import net.wicp.tams.common.web.easyuibean.EasyUINodeConf;
import net.wicp.tams.commons.apiext.IOUtil;
import net.wicp.tams.commons.apiext.StringUtil;
import net.wicp.tams.component.SymbolConstantsCus;
import net.wicp.tams.component.assistbean.Menu;
import net.wicp.tams.component.assistbean.Module;
import net.wicp.tams.component.services.ISupportedLocales;
import net.wicp.tams.component.tools.TapestryAssist;

@Import(stylesheet = { "${path.comassets}/css/layout1.css" }, stack = "easyuistack")
@Events({ SymbolConstantsCus.EVENT_SWITCHMENU })
@Slf4j
public class Layout1 {
	@Data
	public static class DlgBean {
		private String id;
		private String name;
		private String opt="dlg";//有"dlg和fun"
	}

	@Inject
	private AssetSource assetSource;
	@Inject
	protected Request request;
	@Inject
	protected RequestGlobals requestGlobals;
	@InjectService("locales")
	protected ISupportedLocales supportedLocales;

	@Inject
	protected ComponentResources resources;

	@Inject
	@Symbol(SymbolConstants.CONTEXT_PATH)
	@Property
	protected String contextPath;

	@Inject
	@Symbol(SymbolConstantsCus.PATH_COMASSETS)
	private String rjzjhpath;

	@Property
	protected String lan = supportedLocales.getCurLocale().getLanguage();// 当前选择语言
	/***
	 * home页面地址，相对地址, 默认为：classpath
	 * 如果是context:则设置为|，如：context|resource/images/tool_ico/
	 */
	@Parameter(defaultPrefix = BindingConstants.LITERAL)
	@Property
	private String home;
	/**
	 * 所有模块，方便字符形式
	 */
	@Parameter(defaultPrefix = BindingConstants.LITERAL)
	private JSONArray modules;
	/***
	 * 所有模块，优先级高于modules
	 */
	@Parameter(defaultPrefix = BindingConstants.PROP)
	private List<Module> moduleList;
	@Property
	private Module module;
	/***
	 * Layout的对话框 id:对话框的ID，name：显示的菜单名
	 * 
	 */
	@Parameter(defaultPrefix = BindingConstants.LITERAL)
	private JSONArray dlgs;

	public List<DlgBean> getDlgList() {
		if (dlgs == null || dlgs.length() == 0) {
			return CollectionFactory.newList();
		}
		List<DlgBean> retlist = com.alibaba.fastjson.JSONObject.parseArray(dlgs.toString(true), DlgBean.class);
		return retlist;
	}

	@Property
	private DlgBean dlg;

	/**
	 * 是否需要语言切换
	 */
	@Parameter(defaultPrefix = BindingConstants.LITERAL, value = "false")
	@Property
	private boolean isLan;

	/**
	 * icon的存放目录
	 */
	@Parameter(defaultPrefix = BindingConstants.LITERAL)
	private String iconDir;

	public List<Module> getModuleList() {
		if (resources.isBound("moduleList")) {
			return moduleList;
		} else if (resources.isBound("modules")) {
			List<Module> moduleList = com.alibaba.fastjson.JSONObject.parseArray(modules.toString(true), Module.class);
			return moduleList;
		} else {
			return CollectionFactory.newList();
		}
	}

	public String getModuleTitle() {
		return supportedLocales.getConvert().getStr(StringUtil.isNull(module.getAlt()) ? "缺少模块名" : module.getAlt());
	}

	public Asset getModuleImageB() {
		Asset asset = null;
		try {
			asset = assetSource
					.getExpandedAsset(IOUtil.mergeFolderAndFilePath(iconDir.replace("|", ":"), module.getIconB()));
		} catch (Throwable e) {
			asset = assetSource.getExpandedAsset(String.format("%s/images/layout1/icons/default_b.png", rjzjhpath));
		}
		return asset;
	}

	public Asset getModuleImageW() {
		Asset asset = null;
		try {
			asset = assetSource
					.getExpandedAsset(IOUtil.mergeFolderAndFilePath(iconDir.replace("|", ":"), module.getIconW()));
		} catch (Throwable e) {
			asset = assetSource.getExpandedAsset(String.format("%s/images/layout1/icons/default_w.png", rjzjhpath));
		}
		return asset;
	}

	// 切换事件
	public Object getSwitchMenuLink() {
		Link link = resources.createEventLink("doSwitchmenu");
		return link.toAbsoluteURI();
	}

	StreamResponse onDoSwitchmenu() {
		final String moduleId = request.getParameter("moduleId");
		CaptureResultCallback<List<Menu>> callback = new CaptureResultCallback<List<Menu>>();
		resources.triggerEvent(SymbolConstantsCus.EVENT_SWITCHMENU, new Object[] { moduleId }, callback);
		List<Menu> menus = callback.getResult();

		EasyUINodeConf conf = new EasyUINodeConf("id", "resName", "parentId");
		conf.setAttrCols("resValue", "resType");
		conf.setIsRoot(new Predicate() {
			@Override
			public boolean evaluate(Object object) {
				return moduleId.equalsIgnoreCase(String.valueOf(object));
			}
		});
		conf.setTextConvert(supportedLocales.getConvert("resName"));
		List<EasyUINode> retlist = CollectionFactory.newList();
		try {
			retlist = EasyUiAssist.getTreeRoot(menus, conf);
		} catch (Exception e) {
			log.error("生成模块树错误", e);
		}
		String json = EasyUiAssist.getTreeFromList(retlist);
		return TapestryAssist.getTextStreamResponse(json);
	}

}
